package com.easydisk.common.util;


import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.net.NetUtil;
import cn.hutool.core.util.IdUtil;

import javax.annotation.PostConstruct;

/**
 * 雪花算法id生成器
 */
public class IdGenerator {

    //第几号机房
    private static   long workerId = 0;
    //第几号机器
    private static final  long datacenterId = 1;
    private static final Snowflake snowflake =
            IdUtil.getSnowflake(workerId, datacenterId);

    //构造后开始执行，加载初始化工作
    @PostConstruct
    public void init(){
        try{
            //获取本机的ip地址编码
            workerId = NetUtil.ipv4ToLong(NetUtil.getLocalhostStr());
//            log.info("当前机器的workerId: " + workerId);
        }catch (Exception e){
//            log.warn("当前机器的workerId获取失败 ----> " + e);
            workerId = NetUtil.getLocalhostStr().hashCode();
        }
    }

    public synchronized static long nextId(){
        return snowflake.nextId();
    }



}
